import React, { PureComponent } from 'react'
import { Button, Form, Input, InputNumber, Select, Icon, Alert, notification } from 'antd'
import Modal from 'kenote-react-admin-modal'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsUserActions } from 'reduxs'
import { HttpServices, REDUX_FETCH_TIMEOUT, validRule, getTeamFlag } from 'services/utils'
import { getToken, setToken } from 'services/token'
import _ from 'lodash'
import 'styles/modal.scss'

const FormItem = Form.Item
const TextArea = Input.TextArea
const Option = Select.Option

@connect(
  state => ({
    createPending   : state.AdminsUser.createPending,
    createError     : state.AdminsUser.createError,
    createMessage   : state.AdminsUser.createMessage,
    listData        : state.AdminsUser.listData,
    groupList       : state.AdminsGroup.listData,
    auth            : state.Passport.auth,
    rules           : state.Passport.rules
  }),
  dispatch => ({
    actions: bindActionCreators({...adminsUserActions}, dispatch)
  })
)
@Form.create()
export default class AddAdminsUserModal extends PureComponent {

  constructor (props) {
    super(props)
    this.state = {
      disabled: true,
      alert: null,
      password_eye: false,
    }
    this._Modal = null
    this._Form = null
  }
  
  componentWillReceiveProps (nextProps) {
    const { createError, createMessage } = nextProps
    if (createError > 0 && createMessage !== this.props.createMessage) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={createMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
    if (createError === 0 && createMessage !== this.props.createMessage) {
      this._Modal.handleOnCancel()
      notification.info({
        message: `系统提示`,
        description: `新用户创建成功！`,
        duration: 8,
        placement: 'bottomRight'
      })
    }
  }
  
  render () {
    const { visible, onCancel, form, createPending, auth, groupList, rules } = this.props
    const { getFieldDecorator } = form
    const { group } = auth
    const options = {
      ref: view => this._Modal = view,
      visible: visible,
      onCancel: onCancel,
      title: '创建新用户',
      footer: [
        <Button
          onClick={() => this._Modal.handleOnCancel()}
          >
          取消
        </Button>,
        <Button
          type="primary"
          loading={createPending}
          onClick={this.handleSubmit}
          >
          确定
        </Button>
      ],
      width: 600,
      maskClosable: false
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    return (
      <Modal {...options}>
        <br />
        <Form 
          ref={ view => this._Form = view }
          layout="horizontal" 
          onSubmit={this.handleSubmit}
          >
          {createPending ? null : (
            <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
              {this.state.alert ? this.state.alert : null}
            </QueueAnim>
          )}
          <FormItem 
            {...formItemLayout} 
            label="用户名" 
            hasFeedback
            >
            {getFieldDecorator('username', {
              rules: [
                { required: true, message: '用户名不能为空!' },
                { validator: this.checkUsername.bind(this, rules['username']) },
                { validator: this.checkFindUsername.bind(this, rules['username']) }
              ]
            })(
              <Input />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="用户组" 
            hasFeedback
            >
            {getFieldDecorator('group', {
              rules: [{ required: true, message: '请选择用户组!' }],
            })(
              <Select 
                size="Small"
                placeholder="请选择用户组..."
                >
                {groupList && _.filter(groupList, o => o.level < 9999 && (auth.group.level !== 9999 ? getTeamFlag(o.team, auth) : true)).map((item, i) => {
                  return (
                    <Option 
                      key={i} 
                      value={item._id} 
                      disabled={group.level <= item.level || (!getTeamFlag(item.team, auth) && auth.group.level !== 9999)}
                      >
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="登录密码" 
            >
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: '登录密码不能为空!' },
                { validator: this.checkNewPassword.bind(this, rules['password']) }
              ],
            })(
              <Input 
                type={this.state.password_eye ? 'text' : 'password'} 
                suffix={(
                  <Icon 
                    type={this.state.password_eye ? 'eye' : 'eye-o'} 
                    onClick={this.handleLookPassword}
                    style={{ fontSize: 16, color: '#bfbfbf' }}
                    />
                )} 
                />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="E-mail" 
            hasFeedback
            >
            {getFieldDecorator('email', {
              rules: [
                { required: true, message: 'E-mail不能为空!' },
                { validator: this.checkEmail.bind(this, rules['email']), message: 'E-mail格式错误' },
                { validator: this.checkFindEmail.bind(this, rules['email']) }
              ],
              //initialValue: this.state.fieldByEmail
            })(
              <Input />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="昵称" 
            >
            {getFieldDecorator('nickname', {
              rules: [
                { validator: this.checkNickname.bind(this, rules['nickname']), message: '昵称格式错误' }
              ],
            })(
              <Input style={{ width: 250 }} />
            )}

            <Button 
              type="dashed"
              style={{ marginLeft: 10 }}
              disabled={_.isEmpty(_.trim(form.getFieldsValue()['username']))}
              onClick={this.handleCopyUsername}
              >
              从用户名复制
            </Button>
          </FormItem>
        </Form>
      </Modal>
    )
  }
  
  handleSubmit = (e) => {
    e && e.preventDefault()
    const { auth } = this.props
    if (auth.group.flag.indexOf('9012') === -1 && auth.group.level !== 9999) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={'您没有操作此项功能的权限'}
          type="error"
          showIcon
          key="aaa"
        />
      )})
      return
    }
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.actions.create(values)
      }
    })
  }

  handleLookPassword = () => {
    this.setState({ password_eye: !this.state.password_eye })
  }

  handleCopyUsername = () => {
    let { username } = this.props.form.getFieldsValue()
    this.props.form.setFieldsValue({ nickname: username })
  }

  checkUsername (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '用户名格式错误')
    }
    callback()
  }

  async checkFindUsername (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (validByValue.valid) {
      let header = { Authorization: getToken() }
      let result = await HttpServices.GET(`/admins/user/username`, { v: _.trim(value) }, header)
      if (result.Status.code > 0) {
        callback(result.Status.message)
      }
    }
    callback()
  }

  checkNewPassword (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '密码格式错误')
    }
    callback()
  }

  checkEmail (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || 'E-Mail格式错误')
    }
    callback()
  }

  async checkFindEmail (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (validByValue.valid) {
      let header = { Authorization: getToken() }
      let result = await HttpServices.GET(`/admins/user/email`, { v: _.trim(value) }, header)
      if (result.Status.code > 0) {
        callback(result.Status.message)
      }
    }
    callback()
  }

  checkNickname (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '昵称格式错误')
    }
    callback()
  }
}